//
//  NSString+YYUtil.m
//  lanfanglian
//
//  Created by Galaxy Hold on 2020/8/10.
//  Copyright © 2020 Galaxy Hold. All rights reserved.
//  https://blog.51cto.com/u_16099279/7371308

#import "NSString+YYUtil.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (YYUtil)

//生成随机字符串
+(NSString *)generateRandomLetter:(int)length
{
   NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
   NSMutableString *resultStr = [[NSMutableString alloc] init];
   srand((unsigned)time(0));
   for (int i = 0; i < length; i++)
   {
       unsigned index = arc4random_uniform(sourceStr.length) % [sourceStr length];
       NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
       [resultStr appendString:oneStr];
   }
   return resultStr;
   
}

+ (NSString *)base64Decode:(NSString *)str{
    NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:0];
    return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}

//MARK: ===判断是否由中文、字母或数字组成
+ (BOOL)isInputRuleAndBlank:(NSString*)charStr {
    //是否含有汉字
    BOOL isChinese = [self includeChineseWithStr: charStr];
    //是否含有英文字母数字
    int isEngNum = [self checkIsHaveNumAndLetter: charStr];
    return isChinese || (isEngNum != 4);
}

//MARK: ===判断是否是纯汉字
+ (BOOL)isChineseWithStr:(NSString*)charStr{
    
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject: charStr];
}

//MARK: ===判断是否含有汉字
+ (BOOL)includeChineseWithStr:(NSString*)charStr{
    
    for(int i=0; i< [charStr length];i++)
    {
        int a =[charStr characterAtIndex: i];
        if( a >0x4e00&& a <0x9fff){
            return YES;
        }
    }
    return NO;
}

//MARK: ===判断字符串中包含数字和字母的几种情况
+ (int)checkIsHaveNumAndLetter:(NSString*)charStr{
    //数字条件
    NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    //符合数字条件的有几个字节
    NSUInteger tNumMatchCount = [tNumRegularExpression numberOfMatchesInString: charStr
                                                                       options: NSMatchingReportProgress
                                                                         range: NSMakeRange(0, charStr.length)];
    
    //英文字条件
    NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    //符合英文字条件的有几个字节
    NSUInteger tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString: charStr
                                                                             options:NSMatchingReportProgress
                                                                               range:NSMakeRange(0, charStr.length)];
    
    if (tNumMatchCount == charStr.length) {
        //全部符合数字，表示沒有英文
        return 1;
    } else if (tLetterMatchCount == charStr.length) {
        //全部符合英文，表示沒有数字
        return 2;
    } else if (tNumMatchCount + tLetterMatchCount == charStr.length) {
        //符合英文和符合数字条件的相加等于密码长度
        return 3;
    } else {
        return 4;
        //可能包含标点符号的情況，或是包含非英文的文字，这里再依照需求详细判断想呈现的错误
    }
    
}

//MARK: NOTE ==判断手机号码，1开头的十一位数字
+ (BOOL)CheckMobileInput:(NSString *)text {
    if (text.length != 11)
    {
        return NO;
    }

    NSString *Regex = @"1\\d{10}";
    NSPredicate *validateMobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [validateMobile evaluateWithObject: text];
}

/// 包含字母或者数字其中一种或者两种都包含
- (BOOL)isOnlyAlphaAndNumeric{
    NSCharacterSet *set = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
    return ([self rangeOfCharacterFromSet:set].location == NSNotFound);
}
//判断是否有中文
+(BOOL)hasChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}

//MARK: 验证手机号码
+(BOOL)validateMobile:(NSString *)mobileNum{
    if (mobileNum.length != 11)
    {
        return NO;
    }
    
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,175,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[56]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";

    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

/**
 * 大陆地区固话
 * 号码：七位或八位
 */
+ (BOOL)isFixedTelephone:(NSString *)phoneNum {
    //去除"-"、"（）"、"()"按格式样式去除
    phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@"-" withString:@""];
    phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@"(" withString:@""];
    phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@")" withString:@""];
    phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@"（" withString:@""];
    phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@"）" withString:@""];
    NSString * FT = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    //^(0\d{2,3})?[- ]?\d{7,8}$
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", FT];
    return [regextestcm evaluateWithObject:phoneNum];
}


//MARK: NOTE==== 去除数字和字母以外的所有字符
+ (NSString *)removalSpecialCharacters:(NSString *)charStr{
    NSCharacterSet *setToRemove = [[NSCharacterSet characterSetWithCharactersInString: ALPHANUM_FBX] invertedSet];
    NSString *handleChar  = [[charStr componentsSeparatedByCharactersInSet: setToRemove] componentsJoinedByString: @""];
    return handleChar;
}

//MARK: 利用正则表达验证 固话+移动电话
+ (BOOL)isTelephoneOrMobilePhone:(NSString *)phoneNum {
    BOOL result = NO;
    NSString * FT = @"^(((\\d{3,4}-)?[0-9]{7,8})|(1(3|4|5|6|7|8|9)\\d{9}))$";
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", FT];
    result = [regextestcm evaluateWithObject:phoneNum];
    if (!result) {
        result = ([NSString isFixedTelephone:phoneNum]||[NSString validateMobile:phoneNum]);
    }
    return  result;
}


//MARK: 利用正则表达式验证邮箱
+(BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{0,100}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//MARK: 校验密码格式(必须是数字,字母其中的一种)
+(BOOL)isValidatePassword:(NSString *)password {
    NSString *regex = @"^[0-9a-zA-Z].*";
    NSPredicate *passwordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [passwordTest evaluateWithObject:password];
}

//MARK: 密码校验,8到16位  必须大小写字母,数字
+(BOOL)validatePassword:(NSString*)password
{
    NSString *pattern =@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,16}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    return  [pred evaluateWithObject:password];
}

//MARK: 验证码检验 6位数字
+(BOOL)validateVerificationCode:(NSString*)code
{
    NSString *pattern =@"[0-9]{6}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    return  [pred evaluateWithObject:code];
}

//MARK: 用户名校验
+(BOOL)validateUserName:(NSString*)userName
{
    NSString *pattern = @"[0-9a-zA-Z_ -]{3,20}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    return  [pred evaluateWithObject:userName];
}

//MARK: MAC地址校验
+(BOOL)validateMacAddress:(NSString*)macAddr
{
    NSString *pattern =@"^([0-9a-fA-F]{2})(([/\s:-][0-9a-fA-F]{2}){5})$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    return  [pred evaluateWithObject:macAddr];
}

//MARK: 车牌号验证
/**
 ^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$
 ^[\u4e00-\u9fa5]{1}代表以汉字开头并且只有一个，这个汉字是车辆所在省的简称
 [A-Z]{1}代表A-Z的大写英文字母且只有一个，代表该车所在地的地市一级代码
 [A-Z_0-9]{5}代表后面五个数字是字母和数字的组合。
 ^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{3}$如果是这种格式的话，英文字母大小写都可以。但是最好在后台进行转换
 */
+ (BOOL) checkCarNumber:(NSString *)CarNumber{
    NSString *bankNum = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",bankNum];
    BOOL isMatch = [pred evaluateWithObject:CarNumber];
    return isMatch;
}


//MARK: NOTE==== 校验空对象
+ (NSString *)checkNull:(id)obj defaultValue:(NSString *)value{
    if ([obj isEqual:[NSNull null]] || obj == nil || obj == (id)kCFNull) {//null类型
        return value;
    }else if ([obj isKindOfClass:[NSString class]]) {//字符串类型
        if ([obj isEqualToString:@""]||
            [obj isEqualToString:@"null"]||
            [obj isEqualToString:@"NIL"]||
            [obj isEqualToString:@"Nil"]||
            [obj isEqualToString:@"nil"]||
            [obj isEqualToString:@"NULL"]||
            [obj isEqualToString:@"Null"]||
            [obj isEqualToString:@"NULL"]||
            [obj isEqualToString:@"(NULL)"]||
            [obj isEqualToString:@"(Null)"]||
            [obj isEqualToString:@"(null)"]||
            [obj isEqualToString:@"<NULL>"]||
            [obj isEqualToString:@"<Null>"]||
            [obj isEqualToString:@"<null>"]) {
            return value;
        }else{
            return obj;
        }
    }else if ([obj isKindOfClass:[NSNumber class]]) {//Number类型
        return [NSString stringWithFormat:@"%@",obj];
    }else{//其它类型
        return value;
    }

}

//MARK: NOTE==== 保留小数点后两位，不足补小数点或者0.
+ (NSString*)fbxReturnFormatter:(NSString*)stringNumber
{
    stringNumber = [NSString stringWithFormat:@"%@", stringNumber];
    if([stringNumber rangeOfString: @"."].location == NSNotFound) {//无小数点
        NSString *string_comp = [NSString stringWithFormat: @"%@.00", stringNumber];
        return string_comp;
        
    }else{//有小数点
        NSArray *arrays = [stringNumber componentsSeparatedByString: @"."];
        NSString *s_f   = [arrays objectAtIndex: 0];
        NSString *s_e   = [arrays objectAtIndex: 1];
        if(s_e.length > 2) {//最多两位小数
            s_e = [s_e substringWithRange: NSMakeRange(0, 2)];
            
        }else if(s_e.length == 1){
            s_e = [NSString stringWithFormat: @"%@0", s_e];
            
        }
        
        NSString *string_combine = [NSString stringWithFormat:@"%@.%@", s_f, s_e];
        return string_combine;
    }
    
    return @"";
}

//MARK: NOTE==== 去除数字和字母以外的所有字符, 再计算字符长度
+ (NSUInteger)fbxCalculateCharacterLength:(NSString *)mStr
{
    //去除数字和字母以外的所有字符
    NSString *mString = [self removalSpecialCharacters: mStr];
    return mString.length;
}

//URLEncode
+ (NSString*)fbxEncodeString:(NSString*)unencodedStr {
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                          (CFStringRef)unencodedStr,
                          (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                          NULL,
                          kCFStringEncodingUTF8));
    return encodedString;
}

//判断字符串中是否有空格
+ (BOOL)fbxIsBlank:(NSString*)str {
    NSRange fbxRange = [str rangeOfString: @" "];
    if(fbxRange.location != NSNotFound) {
        //有空格
        return YES;
    }else {
        //没有空格
        return NO;

    }
}


/**
 *  返回带星号的手机号码
 */
+ (NSString *)fbxStarPhoneNumerFromNumerStr:(NSString *)numerStr {
    
    NSString *phoneStr = @"";//手机号码添加 *号
    if ([NSString checkNull: numerStr defaultValue: nil]){
        if (numerStr.length <= 3) {
            phoneStr = numerStr;
        }else if (numerStr.length <= 7){
            phoneStr = [numerStr stringByReplacingCharactersInRange:NSMakeRange(3, numerStr.length - 3)  withString:@"****"];
        }else{
            phoneStr = [numerStr stringByReplacingCharactersInRange:NSMakeRange(3, numerStr.length - 7)  withString:@"****"];
        }
    }
    return phoneStr;
}

/**
 *  返回带星号的名称
 */
+ (NSString *)fbxStarNameFromNumerStr:(NSString *)numerStr {
    
    NSString *nameStr = @"";//手机号码添加 *号
    if ([NSString checkNull: numerStr defaultValue: nil]){
        nameStr = [numerStr stringByReplacingCharactersInRange: NSMakeRange(0, 1) withString:@"*"];
    }
    return nameStr;
}

//===================================================================//

+ (NSDateFormatter *)setNorDateFormatterType:(NSString *)forType {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone: timeZone];
    [formatter setDateFormat: forType];//@"yyyy-MM-dd HH:mm:ss"
    
    return formatter;
}

//MARK: 当前时间戳 加减； 返回的是时间戳
+ (NSInteger)getPastHafHourTime:(double)timeValue {
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDate *pastHalfHour = [currentDate dateByAddingTimeInterval: timeValue]; //1小时后是3600   1小时前是-3600
    NSInteger timeSp = [pastHalfHour timeIntervalSince1970];//系统默认时间格式：@"yyyy-MM-dd HH:mm:ss"
    return timeSp;
}

//MARK: 时间戳 转 标准时间, 自定义时间格式；
+ (NSString*)turnTimeWithTimestamp:(NSInteger)turnTime
                     formatterType:(NSString *)forType {
    
    NSDateFormatter *formatter = [self setNorDateFormatterType: forType];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970: turnTime];
    return [NSString stringWithFormat:@"%@", [formatter stringFromDate:date]];
}

//MARK: 时间转时间戳，自定义时间格式； 返回的是时间戳 （NSInteger类型）
+ (NSInteger)crazyTimeToTimestamp:(NSString *)dataStr
                    formatterType:(NSString *)forType {
    
    NSDateFormatter *formatter = [self setNorDateFormatterType: forType];
    //将字符串按formatter转成nsdate
    NSDate* date = [formatter dateFromString:dataStr];
    NSInteger timeSp = [date timeIntervalSince1970];
    return timeSp;
}

- (NSString *)YYMd5Value {
    
    const char *cStr = [self UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    //surpp
    CC_MD5( cStr, (int)self.length, digest );
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [result appendFormat:@"%02x", digest[i]];
    return result;
}

+ (NSString*)YYSafeTimestampWithDate:(NSDate*)date {
    
    NSString *timestamp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    return timestamp;
}

//MARK: 根据长度 获取一个随机数字符串
+ (NSString*)YYSafeRandomStringWithLength:(NSInteger)length {
    
    NSString *string = [[NSString alloc]init];
    for (int i = 0; i < length; i++) {
        int number = arc4random() % 36;
        if (number < 10) {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
        }else {
            int figure = (arc4random() % 26) + 97;
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            string = [string stringByAppendingString:tempString];
        }
    }
    return string;
}

+ (NSString *)YYSignCodeWithUid:(NSString *)uid
                         random:(NSString *)random
                      phoneName:(NSString *)phoneName
                      phoneUUID:(NSString *)phoneUUID
                        systemV:(NSString *)systemV
                            ver:(NSString *)ver
                      timestamp:(NSString *)time {
    
    static NSString *key = @"wcphp";
    NSString *str = [[NSString stringWithFormat:@"2%@%@%@%@%@%@%@%@",random,phoneName,phoneUUID,systemV,ver,time,uid,key] YYMd5Value];
    return str;
}

//MARK: 时间显示内容
/**
 *  时间戳转成字符串
 *
 *  @param timestamp 时间戳
 *  @param  maxDateFormat  发表时间大于10天 的 日期格式
 *  @return 格式化后的字符串
 */
+ (NSString *)YYTimeFromTimestamp:(NSInteger)timestamp
                    maxDateFormat:(NSString *)maxDateFormat {
    
    NSDateFormatter *dateFormtter = [[NSDateFormatter alloc] init];
    NSDate *d            = [NSDate dateWithTimeIntervalSince1970: timestamp];
    NSTimeInterval late  = [d timeIntervalSince1970]*1; //转记录的时间戳
    NSDate* dat          = [NSDate dateWithTimeIntervalSinceNow: 0];
    NSTimeInterval now   = [dat timeIntervalSince1970]*1;//获取当前时间戳
    NSString *timeString = @"";
    NSTimeInterval cha   = now-late;
    // 发表在1小时之内
    if (cha/3600<1) {
        if (cha/60<1) {
            timeString = @"1";
            
        }else{
            timeString = [NSString stringWithFormat:@"%f", cha/60];
            timeString = [timeString substringToIndex: timeString.length-7];
        }
        timeString = [NSString stringWithFormat:@"%@分钟前", timeString];
        
    }
    // 在1小时以上24小时以内
    else if (cha/3600>1 && cha/86400<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex: timeString.length-7];
        timeString = [NSString stringWithFormat:@"%@小时前", timeString];
    }
    // 发表在24小时以上10天以内
    else if (cha/86400>1 && cha/259200<1){//86400 = 60(分)*60(秒)*24(小时)   3天内
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex: timeString.length-7];
        timeString = [NSString stringWithFormat:@"%@天前", timeString];
        
    }
    // 发表时间大于10天
    else{
        if (!maxDateFormat) {
            maxDateFormat = @"MM/dd";
        }
        
        [dateFormtter setDateFormat: maxDateFormat];
        timeString = [dateFormtter stringFromDate: d];
    }
    
    return timeString;
}



/**
 *  根据格式将时间戳转换成时间
 *
 *  @param timestamp    时间戳
 *  @param formtter 日期格式
 *
 *  @return 带格式的日期
 */
+ (NSString *)YYTimeFromTimestamp:(NSInteger)timestamp formtter:(NSString *)formtter{
    NSDateFormatter *dataFormtter = [[NSDateFormatter alloc] init];
    [dataFormtter setDateFormat: formtter];
    NSDate *date   = [NSDate dateWithTimeIntervalSince1970: timestamp];
    NSString *time = [dataFormtter stringFromDate: date];
    return time;
}
 
/**
 *  获取当前时间戳
 */
+ (NSString *)YYTimeIntervalGetFromNow{
    
    // 获取时间（非本地时区，需转换）
    NSDate * today = [NSDate date];
    NSTimeZone *zone   = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: today];
    // 转换成当地时间
    NSDate *localeDate = [today dateByAddingTimeInterval: interval];
    // 时间转换成时间戳
    NSString *timeSp   = [NSString stringWithFormat:@"%ld",(long)[localeDate timeIntervalSince1970]];
    
    return timeSp;
}


//获取当前时间戳  （以毫秒为单位）
+(NSString *)getNowTimeTimestamp3{

   NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;

   [formatter setDateStyle:NSDateFormatterMediumStyle];

   [formatter setTimeStyle:NSDateFormatterShortStyle];

   [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

   //设置时区,这个对于时间的处理有时很重要

   NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

   [formatter setTimeZone:timeZone];

   NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式

   NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];

   return timeSp;

}


/**
 *  显示时间（几分钟前，几小时前，几天前）
 */
+ (NSString *)YYCompareCurrentTime:(NSInteger)timestamp {

    //把字符串转为NSdate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970: timestamp];;
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate: timeDate];

    long temp = 0;
    NSString *result;

    if (timeInterval/60 < 1) {
        result = [NSString stringWithFormat:@"刚刚"];
        
    }else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟前",temp];

    }else if((temp = temp/60) < 24){
        result = [NSString stringWithFormat:@"%ld小时前",temp];

    }else if((temp = temp/24) < 30){
        result = [NSString stringWithFormat:@"%ld天前",temp];

    }else if((temp = temp/30) < 12){
        result = [NSString stringWithFormat:@"%ld个月前",temp];

    }else{
        temp = temp/12;
        result = [NSString stringWithFormat:@"%ld年前",temp];

    }

    return  result;
}

//MARK: note === 获取随机的UUID
+ (NSString *)getYYRandomUUID {
    
    NSString *uuid = [[NSUUID UUID] UUIDString];
    return uuid;
}

//==========================================================================//

//MARK: NOTE==== 返回整数的字符串
+ (NSString*)fbxReturnIntNum:(NSString*)stringNumber {
    
    stringNumber = [NSString stringWithFormat:@"%@", stringNumber];
    if([stringNumber rangeOfString: @"."].location == NSNotFound) {//无小数点
        return stringNumber;
        
    }else{//有小数点
        CGFloat fNum = ceilf([stringNumber floatValue]);//向上取整
        NSString *string_combine = [NSString stringWithFormat:@"%.0f", fNum];
        return string_combine;//只返回整数
    }
    
    return @"";
}

//MARK: NOTE==== double值为xx.00时，不显示小数点及后两位
+ (NSString *)fbxReturnNumStr:(double)num {
    
    NSString *stringNumber = [NSString stringWithFormat:@"¥%.2f", num];
    NSArray *arrays = [stringNumber componentsSeparatedByString: @"."];
    NSString *s_f   = [arrays objectAtIndex: 0];
    NSString *s_e   = [arrays objectAtIndex: 1];//小数点后两位数
    if ([s_e integerValue] == 0) {//double值为xx.00
        stringNumber = s_f;
    }
    return stringNumber;
}


//MARK: NOTE==== 保留小数点后两位，strIndex大于0，整数值截取到strIndex
+ (NSString*)fbxReturnFormatter:(NSString *)strNum
                  subStrToIndex:(NSUInteger)strIndex {
    
    strNum = [NSString stringWithFormat:@"%@", strNum];
    if([strNum rangeOfString: @"."].location == NSNotFound) {//无小数点
        if (strIndex > 0) {
            if (strNum.length > strIndex) {
                strNum = [strNum substringToIndex: strIndex];
            }
        }
        return strNum;
        
    }else{//有小数点
        NSArray *arrays = [strNum componentsSeparatedByString: @"."];
        NSString *s_f   = [arrays objectAtIndex: 0];
        NSString *s_e   = [arrays objectAtIndex: 1];
        if(s_e.length > 2) {//最多两位小数
            s_e = [s_e substringWithRange: NSMakeRange(0, 2)];
        }
        
        if (strIndex > 0) {
            if (s_f.length > strIndex) {
                s_f = [s_f substringToIndex: strIndex];
            }
        }
        
        NSString *string_combine = [NSString stringWithFormat:@"%@.%@", s_f, s_e];
        return string_combine;
    }
    return @"";
}

//MARK: NOTE==== 金额千位分显示, 比如：￥123,456,789.00
+ (NSString *)fbxAmountThousandBitsWithNumber:(NSNumber *)numb {
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString *newAmount = [formatter stringFromNumber: numb];
    return newAmount;
}

//MARK: NOTE==== 金额分割，并保留两位小数 ￥123,456,789.00
+ (NSString *)formatStringAfterPoint:(NSString *)amtStr{
    
    if (!amtStr||[amtStr length]==0) {
        return @"0.00";
    }
    
    NSDecimalNumber *num=[NSDecimalNumber decimalNumberWithString:amtStr];
    //规定保留两位小数
    NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];

    num = [num decimalNumberByRoundingAccordingToBehavior:handler];
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString *newAmount = [formatter stringFromNumber: num];
    
    if (![newAmount containsString:@"."]) {
        newAmount = [NSString stringWithFormat:@"%@.00",newAmount];
       } else { //小数不足两位
           NSArray *array = [newAmount componentsSeparatedByString:@"."];
           NSString *subNumber = array.lastObject;
           if (subNumber.length == 1) {
               newAmount = [NSString stringWithFormat:@"%@.%@0",array.firstObject, array.lastObject];
           }
       }
    return newAmount;
}


+ (NSString *)stringAfterPoint:(NSString *)amtStr{
    NSDecimalNumber *num=[NSDecimalNumber decimalNumberWithString:amtStr];
    //规定保留两位小数
    NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];

    num = [num decimalNumberByRoundingAccordingToBehavior:handler];
    
    return num.stringValue;
}

//金额 高精度保留两位小数,(无分隔符) 比如：￥123456789.34
+ (NSString *)stringTwoPoint:(NSString *)amtStr{
    if (!amtStr||[amtStr length]==0) {
        return @"0.00";
    }
    NSDecimalNumber *num=[NSDecimalNumber decimalNumberWithString:amtStr];
    //规定保留两位小数
    NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];

    num = [num decimalNumberByRoundingAccordingToBehavior:handler];
    
    NSString *newAmount = num.stringValue;
    
    if (![newAmount containsString:@"."]) {
        newAmount = [NSString stringWithFormat:@"%@.00",newAmount];
       }else { //小数不足两位
           NSArray *array = [newAmount componentsSeparatedByString:@"."];
           NSString *subNumber = array.lastObject;
           if (subNumber.length == 1) {
               newAmount = [NSString stringWithFormat:@"%@.%@0",array.firstObject, array.lastObject];
           }
    }
    
    return newAmount;
}


/**
 *  计算富文本字体宽度
 *
 *  @param lineSpeace 行高
 *  @param font       字体
 *  @param height      字体所占高度
 *
 *  @return 富文本高度
 */
+ (CGFloat)getFbxSpaceLabelHeightWithAttStr:(NSAttributedString *)attStr
                                 lineSpeace:(CGFloat)lineSpeace
                                       font:(UIFont*)font
                                     height:(CGFloat)height {
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    //paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    /** 行高 */
    paraStyle.lineSpacing = lineSpeace;
    // NSKernAttributeName字体间距
    NSDictionary *dic = @{NSFontAttributeName: font,
                          NSParagraphStyleAttributeName:paraStyle,
                          NSKernAttributeName: @1.5f
                          };
    
    CGSize size = [attStr boundingRectWithSize: CGSizeMake(MAXFLOAT, height)
                                       options: NSStringDrawingUsesLineFragmentOrigin
                                       context: nil].size;
    
    return size.width;
}

//MARK: NOTE====获取当前时间
/**
 *  获取当前时间
 *  @param dateFormatStr  时间格式    例如：@"yyyy年MM月dd日"
 *  return dateTime  当前时间
 */
+ (NSString *)getCurrentDateWithDateFormatStr:(NSString *)dateFormatStr {
    
    dateFormatStr = [self checkNull: dateFormatStr defaultValue: @"yyyy/MM/dd"];//默认格式：yyyy/MM/dd
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    [formatter setDateFormat: dateFormatStr];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}


//MARK: note === 获得当前时间的前几天，几个月，几年
+ (NSString *)currentDateFormat:(NSString *)format
                          years:(NSInteger)years
                         months:(NSInteger)months
                           days:(NSInteger)days {
    
    //得到当前的时间
    NSDate *mydate = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: format];
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    NSCalendar *calendar       = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *adcomps  = [calendar components: NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitMonth fromDate: mydate];
    
    [adcomps setYear: years];
    [adcomps setMonth: months];
    [adcomps setDay: days];
    
    NSDate *newdate = [calendar dateByAddingComponents: adcomps toDate: mydate options: 0];
    NSString *beforDate = [dateFormatter stringFromDate:newdate];
    
    return beforDate;
}

//MARK: 时间转时间戳，自定义时间格式； 返回的是时间戳 （NSInteger类型）
+(NSInteger)YYCrazy_timeToTimestamp:(NSString *)dataStr
                      formatterType:(NSString *)formatterType {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone: timeZone];
    [formatter setDateFormat: formatterType];//@"yyyy-MM-dd HH:mm:ss"
    
    //将字符串按formatter转成nsdate
    NSDate* date = [formatter dateFromString:dataStr];
    NSInteger timeSp = [date timeIntervalSince1970];
    return timeSp;
}

//==========================================================================//

- (NSRange)rangeByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet{
    NSUInteger location = 0;
    NSUInteger length = [self length];
    unichar charBuffer[length];
    [self getCharacters:charBuffer];
    for (location = 0; location < length; location++) {
        if (![characterSet characterIsMember:charBuffer[location]]) {
            break;
        }
    }
    return NSMakeRange(location, length - location);
}
- (NSRange)rangeByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet{
    NSUInteger location = 0;
    NSUInteger length = [self length];
    unichar charBuffer[length];
    [self getCharacters:charBuffer];
    for (length = [self length]; length > 0; length--) {
        if (![characterSet characterIsMember:charBuffer[length - 1]]) {
            break;
        }
    }
    return NSMakeRange(location, length - location);
}

- (NSString *)trimWhitespace
{
    NSMutableString *str = [self mutableCopy];
    CFStringTrimWhitespace((__bridge CFMutableStringRef)str);
    return str;
}

- (BOOL)isEmpty
{
    return [[self trimWhitespace] isEqualToString:@""];
}

- (BOOL)isEmptyOrListening{
    return [self isEmpty] || [self hasListenChar];
}

//判断是否为整形
- (BOOL)isPureInt{
    NSScanner* scan = [NSScanner scannerWithString:self];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//判断是否为浮点形
- (BOOL)isPureFloat{
    NSScanner* scan = [NSScanner scannerWithString:self];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

//是否相等
- (BOOL)calculateIsEqual:(NSString *)stringNumer
{
    NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:self];
    NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:stringNumer];
    NSComparisonResult result = [num1 compare:num2];
    if (result == NSOrderedSame) {
        return YES;
    }
    return NO;
}

//是否大于
- (BOOL)calculateIsGreaterThan:(NSString *)stringNumer
{
    NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:self];
    NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:stringNumer];
    NSComparisonResult result = [num1 compare:num2];
    if (result == NSOrderedDescending) {
        return YES;
    }
    return NO;

}
//是否小于
- (BOOL)calculateIsLessThan:(NSString *)stringNumer
{
    NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:self];
    NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:stringNumer];
    NSComparisonResult result = [num1 compare:num2];
    if (result == NSOrderedAscending) {
        return YES;
    }
    return NO;

}

//转换拼音
- (NSString *)transformToPinyin {
    if (self.length <= 0) {
        return self;
    }
    NSString *tempString = [self mutableCopy];
    CFStringTransform((CFMutableStringRef)tempString, NULL, kCFStringTransformToLatin, false);
    tempString = (NSMutableString *)[tempString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
    tempString = [tempString stringByReplacingOccurrencesOfString:@" " withString:@""];
    return [tempString uppercaseString];
}

//是否包含语音解析的图标
- (BOOL)hasListenChar{
    BOOL hasListenChar = NO;
    NSUInteger length = [self length];
    unichar charBuffer[length];
    [self getCharacters:charBuffer];
    for (length = [self length]; length > 0; length--) {
        if (charBuffer[length -1] == 65532) {//'\U0000fffc'
            hasListenChar = YES;
            break;
        }
    }
    return hasListenChar;
}

/**
 计算文字高度，允许换行计算

 @param font  字体
 @param width 文字宽度
 @param minLineHeight 最小行高
 @return 返回文字的高度
 */
- (CGFloat)YYSizeLineFeedWithFont:(UIFont *)font
                        textWidth:(CGFloat)width
                    minLineHeight:(CGFloat)minLineHeight {
    /**
     NSStringDrawingUsesLineFragmentOrigin
     整个文本将以每行组成的矩形为单位计算整个文本的尺寸。
     NSStringDrawingTruncatesLastVisibleLine/NSStringDrawingUsesDeviceMetrics
     计算文本尺寸时将以每个字或字形为单位来计算。
     NSStringDrawingUsesFontLeading
     以字体间的行距（leading，行距：从一行文字的底部到另一行文字底部的间距。）来计算。
     */
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paragraphStyle.lineSpacing = 2.0f;//4.0f;//行距
    paragraphStyle.minimumLineHeight = minLineHeight;//最小行高
    NSDictionary *attributes = @{
                                  NSFontAttributeName:font,
                                  NSParagraphStyleAttributeName: paragraphStyle
                                  };
    CGSize textRect = CGSizeMake(width, MAXFLOAT);
    NSString *text = self;
    //在末尾添加一个换行符，比较准确计算总高度。
//    text = [text stringByAppendingString: @"\n"];
    CGFloat textHeight = [text boundingRectWithSize: textRect
                                            options: NSStringDrawingTruncatesLastVisibleLine
                                                    |NSStringDrawingUsesFontLeading
                                                    |NSStringDrawingUsesLineFragmentOrigin
                                         attributes: attributes
                                            context: nil].size.height;
    return textHeight;
}

// --jsonStringTo字典
- (NSDictionary *)jsonStringToDictionary {
    if (self.length == 0) {
        return nil;
    }
    NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *content = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    return content;
}
// json字符串转数组
- (NSArray *)jsonStringToArray
{
    if (self.length == 0) {
        return nil;
    }
    NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    if ([array isKindOfClass:[NSArray class]]) {
        return array;
    }
    return nil;
}

+(NSAttributedString*)attributeStringWithContent:(NSString*)content  attriFont:(UIFont*)font attriColor:(UIColor*)color attriKey:(NSString*)key;
{
    if(content.length == 0 || ![content containsString:key]){
        return [[NSMutableAttributedString alloc] initWithString:@"--"];
    }
    NSDictionary *attiDic = @{NSFontAttributeName:font,NSForegroundColorAttributeName:color};
    NSMutableAttributedString *attri_content = [[NSMutableAttributedString alloc] initWithString:content];
    NSRange range = [content rangeOfString:key];
    [attri_content setAttributes:attiDic range:range];
    return attri_content;
}

//检查是否全是空字符
+(BOOL)checkIsAllEmptyLater:(NSString*)content
{
    NSString *tem = ValidNullData(content);
    
    while([tem hasPrefix:@" "]){
        tem = [tem substringFromIndex:1];
    }
    return tem.length == 0;
    
}

///参数设置加减项只允许输入正负整数或小数
+(BOOL)checkIsIntOrDecimalNumber:(NSRange)range textFieldContent:(NSString*)textFieldString inputString:(NSString*)string
{
    
    //删除
    if([string isEqualToString:@""]){
        return YES;
    }
    // “-” 必须是第一个位置也可保证只有一个 “-”
   if ([string isEqualToString:@"-"]) {
       if (range.location != 0 ) {
           return NO;
       }
   }
   //只允许输入一个小数点
   if ([textFieldString containsString:@"."] && [string isEqualToString:@"."]) {
       return NO;
   }
   //小数点不能为第一位
   if (textFieldString.length == 0 && [string isEqualToString:@"."]) {
       return NO;
   }
   
  //限制只能输入 "-0123456789."
   NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"-0123456789."];
   //if (textField == self.moneyTF) {//如果是后面那个输入金额的textFiled则限制 限制只能输入 "-0123456789"
      // tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"-0123456789"];
   //}
   BOOL res = YES;
   int i = 0;
   while (i < string.length) {
       NSString * str = [string substringWithRange:NSMakeRange(i, 1)];
       NSRange range = [str rangeOfCharacterFromSet:tmpSet];
       if (range.length == 0) {
           res = NO;
           break;
       }
       i++;
   }
   return res;
    
    
}
@end
